package com.car.carmgr.util;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/*监听controller异常的工具类*/
@RestControllerAdvice
public class HzdlExceptionHander {
    /*执行该方法说明程序出错了*/
    @ExceptionHandler(value = Exception.class)
    public Object errorHander(HttpServletRequest request, HttpServletResponse response,Exception e){

        //X-Requested-With: XMLHttpRequest  AJAX请求都附带该属性以及值
        String header = request.getHeader("X-Requested-With");
        if(header != null && header.equals("XMLHttpRequest")){
            //ajax请求
            //TODO ajax需要转为统一的对象，比如AjaxResult对象
            return AjaxResult.error(-1,e.getMessage());
        }else{
            ModelAndView mav = new ModelAndView();
            mav.setViewName("forward:/error.jsp");
            mav.addObject("msg",e.getMessage());
            mav.addObject("url",request.getRequestURI());
            return mav;
        }
    }
}
